import {createRouter, createWebHistory} from 'vue-router'
import {notification} from "ant-design-vue"
import store from '@/store'

const routes = [
  {
    path: '',
    redirect: '/welcome'
  },
  {
    path: '/',
    name: 'Main',
    component: () => import('../views/Main.vue'),
    meta: {
      loginRequired: true
    },
    children: [
      {
        path: 'welcome',
        name: 'Welcome',
        component: () => import('@/views/main/Welcome.vue'),
        meta: {title: '欢迎'}
      },
      {
        path: 'my-ticket',
        name: 'MyTicket',
        component: () => import('@/views/main/MyTicket.vue'),
        meta: {title: '我的车票'}
      },
      {
        path: 'passenger',
        name: 'Passenger',
        component: () => import('@/views/main/Passenger.vue'),
        meta: {title: '旅客管理'}
      },
      {
        path: 'ticket',
        name: 'Ticket',
        component: () => import('@/views/main/Ticket.vue'),
        meta: {title: '车票查询'}
      },
      {
        path: 'order',
        name: 'Order',
        component: () => import('../views/main/Order.vue'),
        meta: {title: '车票购买'}
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "about" */ '../views/Login.vue'),
    meta: {title: '登录'}
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由拦截器 检验是否登录
router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title} | 12306`
  // 要不要对meta.loginRequire属性做监控拦截
  const isLogin = to.matched.some(item => item.meta.loginRequired)
  if (isLogin) {
    const _member = store.state.member;
    if (!_member.token) {
      notification.error({ description: "未登录或登录超时" });
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
})


export default router
